
<!-- <nav class="nav">
  <div class="container">
    <h1 class="logo"><a href="/">LoginDemo</a></h1>
    <ul>
      <li><a href="/" use:link class="current">Home</a></li>
      <li><a href="/login" use:link>Login</a></li>
    </ul>
  </div>
</nav> -->
<script>

// const nav = document.querySelector('.nav')
// window.addEventListener('scroll', fixNav)

// function fixNav() {
//     if(window.scrollY > nav.offsetHeight + 150) {
//         nav.classList.add('active')
//     } else {
//         nav.classList.remove('active')
//     }
// }
    // import LoginRegister from '../pages/LoginRegister'
import {onMount} from 'svelte';
import axios from "axios";  

import  {push} from "svelte-spa-router";

let message = 'You are not logged in';
let userId = -1;
let userLoged;
let respon;
onMount(async () => {
    // const response = await axios.post('user');
    
    // if (response.status === 200) {
    //     message = `Hi ${response.data.name}`;
    // } else {
    //     await push('/login');
    // }
    fetch(`http://8.130.73.191/api/user`, {
      method: "POST",
      // headers: {
      //   "Access-Control-Allow-Origin": "*",
      //   "Content-Type":"application/json",
      // },
      body: JSON.stringify({id: userId})
    }).then(async (res)=>{
      respon = await res.json();
      console.log(respon.status)
      if(respon.status === 200) {
        message = `Hi ${respon.user_name}`;
        userId = respon.user_id;
      } else {
        console.log("you already logged in!")
        await push('/login');
      }
    })
});

// fetch("http://localhsot:9000/user", {
//     method: "GET",
//     headers: {
//       "Content-Type": "application/json",
//     },
//   })
//   .then(async(res)=> {
//     users = await res.json();

//   })
//   .catch((err)=>{
//     console.log("error fetching users from backend: ", err);
//   })

$: logout = async () => {
    // await axios.post('logout', {}, {withCredentials: true});

    // axios.defaults.headers.common['Authorization'] = '';

    // await push('/login');
    fetch(`http://8.130.73.191/api/logout`, {
      method: "POST",
      // headers: {
      //   "Access-Control-Allow-Origin": "*",
      //   "Content-Type":"application/json",
      // },
      body: JSON.stringify({id: userId})
    }).then(async (res)=>{
      respon = await res.json();
      console.log(respon.status)
      if(respon.status === 200) {
        message = `You are not logged in yet`;
        userId = -1;
        await push('/login');
      } else {
        console.log("logout error")
      }
    })
}

</script>
<link
  rel="stylesheet"
  href="https://cdnjs.cloudflare.com/ajax/libs/tailwindcss/1.8.11/tailwind.min.css"
  integrity="sha512-KO1h5ynYuqsFuEicc7DmOQc+S9m2xiCKYlC3zcZCSEw0RGDsxcMnppRaMZnb0DdzTDPaW22ID/gAGCZ9i+RT/w=="
  crossorigin="anonymous"
/>

<div class="hero">
  <div class="container">
    <h1>{message}</h1>
    <p>Have a good day!</p>

  </div>

    <div class="contaiinerBtn">
  </div>

</div>


<!-- <section class="container content">
  <h2>Content One</h2>
  <p>Lorem, ipsum dolor sit amet consectetur adipisicing elit. Ratione dolorem voluptates eveniet tempora ut cupiditate magnam, sapiente, hic quo in ipsum iste soluta eaque perferendis nihil recusandae dolore officia aperiam corporis similique. Facilis quos tempore labore totam! Consectetur molestiae iusto ducimus error reiciendis aspernatur dolor, modi dolorem sit architecto, voluptate magni sunt unde est quas? Voluptates a dolorum voluptatum quo perferendis aut sit. Aspernatur libero laboriosam ab eligendi omnis delectus earum labore, placeat officiis sint illum rem voluptas ipsum repellendus iste eius recusandae quae excepturi facere, iure rerum sequi? Illum velit delectus dicta et iste dolorum obcaecati minus odio eligendi!</p>

  <h3>Content Two</h3>
  <p>Lorem ipsum dolor sit amet consectetur, adipisicing elit. Pariatur provident nostrum possimus inventore nisi laboriosam consequatur modi nulla eos, commodi, omnis distinctio! Maxime distinctio impedit provident, voluptates illo odio nostrum minima beatae similique a sint sapiente voluptatum atque optio illum est! Tenetur tempora doloremque quae iste aperiam hic cumque repellat?</p>
</section> -->





<!-- 




 <script lang="ts">
  // ---------------------------------------------------------
  //  Global Imports
  // ---------------------------------------------------------
  import Fa from 'svelte-fa/src/fa.svelte'
  import { faPlus } from '@fortawesome/free-solid-svg-icons';
  // ---------------------------------------------------------
  //  Type Imports
  // ---------------------------------------------------------
  import type { NoteType } from '@/types/app'
  // ---------------------------------------------------------
  //  Component Imports
  // ---------------------------------------------------------
  import Note from '@/components/Note.svelte'
  import EditNoteModal from '@/components/EditNoteModal.svelte'
  import DeleteNoteModal from '@/components/DeleteNoteModal.svelte'
  // ---------------------------------------------------------
  //  Varaible Declarations
  // ---------------------------------------------------------
  let notesJSONString: string = localStorage.getItem('notes')
  let notes: Array<NoteType> = []
  // Notes initialization
  if (notesJSONString) {
    try {
      notes = JSON.parse(notesJSONString) as NoteType[]
    } catch(err) {
      console.error(err)
    }
  } else {
    notes = [
      {
        id: 1,
        title: 'Some Note',
        content: 'This note is about this and that',
        date: '20210806123021',
        isFavorite: false,
        tags: ['test', 'text']
      },
      {
        id: 2,
        title: 'Another Note',
        content: 'This is yet another note about this and that',
        date: '20210806133021',
        isFavorite: false,
        tags: ['test', 'text', 'extra']
      },
      {
        id: 3,
        title: 'Lorem ipsum',
        content: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi in bibendum tellus. Aenean bibendum purus id turpis hendrerit tristique vitae nec lacus. Nam viverra elementum nisl. Donec non tempus arcu. Etiam iaculis ex nec hendrerit tincidunt. Vivamus elementum velit dui, non hendrerit purus condimentum ut. In convallis mauris eget consequat tempus. Pellentesque auctor a massa ac suscipit. Donec id metus suscipit, interdum tortor at, semper massa. Donec eget finibus purus, sed varius mi. Etiam a dui eget tortor auctor pulvinar eu ac lectus. Duis non diam molestie, efficitur massa non, suscipit massa. Etiam dictum eros quis ullamcorper scelerisque. Donec fermentum id ipsum vitae ullamcorper. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Cras pharetra diam sed fringilla dictum.',
        date: '20210804133021',
        isFavorite: true,
        tags: ['Lorem', 'ipsum']
      }
    ]
  }
  // ---------------------------------------------------------
  //  Edit Modal Methods
  // ---------------------------------------------------------
  // For Editing
  let noteToEdit: NoteType | Record<string, unknown> | undefined
  let showEditModal = false
  /**
   * Display the Note details modal
   *
   * @param {NoteType} note
   */
  const openEditNote = (note?: NoteType) => {
    noteToEdit = {}
    if (note) {
      noteToEdit = note
    }
    showEditModal = true
  }
  /**
   * Close the Note details modal
   *
   */
  const closeEditModal = () => {
    noteToEdit = {}
    showEditModal = false
  }
  // ---------------------------------------------------------
  //  Delete Modal Methods
  // ---------------------------------------------------------
  // For Deleting
  let noteToDelete: NoteType | Record<string, unknown> | undefined
  let showDeleteModal = false
  /**
   * Display the Note details modal
   *
   * @param {NoteType} note
   */
  const openDeleteNote = (event: CustomEvent) => {
    const deleteNoteIndex = event.detail as number
    const noteIndex = notes.findIndex(item => item.id === deleteNoteIndex)
    if (noteIndex !== -1) {
      noteToDelete = notes[noteIndex]
      showDeleteModal = true
    }
  }
  /**
   * Close the Note details modal
   *
   */
  const closeDeleteModal = () => {
    noteToDelete = {}
    showDeleteModal = false
  }
  // ---------------------------------------------------------
  //  Note Related Methods
  // ---------------------------------------------------------
  /**
   * Save notes in the local storage
   */
  const saveNotesToStorage = () => {
    // for reactivity purposes
    notes = notes
    // save it in the local storage
    localStorage.setItem('notes', JSON.stringify(notes))
  }
  /**
   * Toggle the favorite flag of a given post
   * and save the changes to local storage
   *
   * @param {CustomEvent} event
   * @param {Number} event.detail
   */
  const toggleFavorite = (event: CustomEvent) => {
    const noteId: number = (event.detail as number)
    const note = notes.find(item => item.id === noteId)
    if (note) {
      note.isFavorite = !note.isFavorite
      saveNotesToStorage()
    }
  }
  /**
   * Update the eixting note or add the new note
   *
   * @param {CustomEvent} event
   * @NoteType {Number} event.detail
   */
  const saveNote = (event: CustomEvent) => {
    closeEditModal()
    const note = event.detail as NoteType
    const noteIndex = notes.findIndex(item => item.id === note.id)
    
    if (noteIndex !== -1) {
      notes[noteIndex] = note    
    } else {
      notes.push(note)
    }
    saveNotesToStorage()
  }
  /**
   * 
   * @param {CustomEvent} event
   * @param {Number} event.detail
   */
  const deleteNote  = (event: CustomEvent) => {
    closeDeleteModal()
    closeEditModal()
    const deleteNoteIndex = event.detail as number
    const noteIndex = notes.findIndex(item => item.id === deleteNoteIndex)
    
    if (noteIndex !== -1) {
      notes.splice(noteIndex, 1)
    }
    console.log(notes)
    saveNotesToStorage()
  }
</script>

<main>
  <div class="note-card-container">
    <div class="note-card-add" on:click="{() => { openEditNote() }}">
      <Fa icon={faPlus} color="#afaeae" size="3x" />
    </div>

    {#each notes as note (note.id)}
      <Note
        {...note}
        on:click="{() => { openEditNote(note) }}"
        on:toggleFavorite="{toggleFavorite}"
      />
    {/each}
  </div>
</main>

{#if showEditModal}
  <EditNoteModal
    {...noteToEdit}
    on:save="{saveNote}"
    on:delete="{openDeleteNote}"
    on:close="{closeEditModal}"
  />
{/if}

{#if showDeleteModal}
  <DeleteNoteModal
    {...noteToDelete}
    on:delete="{deleteNote}"
    on:close="{closeDeleteModal}"
  />
{/if}

<style lang="scss">
  main {
    padding: 2em;
    margin: 0 auto;
    width: 100vw;
    box-sizing: border-box;
  }
  .note-card {
    &-add {
      background-color: #d6d4d4;
      display: flex;
      justify-content: center;
      align-items: center;
      box-shadow: none;
      border: 4px dashed #a29f9f;
      width: 144px;
      height: 189px;
      color: #a29f9f;
      margin-right: 15px;
      padding: 15px;
      border-radius: 10px;
      &:hover {
          background-color: #c5c5c5;
      }
    }
    &-container {
      display: flex;
    }
  }
</style> -->






<!-- <div class="container mt-5 text-center">
    <h3>{message}</h3>

    <a href="javascript:void(0)" class="btn btn-lg btn-primary"
      on:click={logout}
    >Logout</a>
</div> -->


<style>
/* .form-signin {
	width: 100%;
	max-width: 330px;
	padding: 15px;
	margin: auto;
}

.form-signin .checkbox {
	font-weight: 400;
}

.form-signin .form-floating:focus-within {
	z-index: 2;
}

.form-signin input[type="email"] {
	margin-bottom: -1px;
	border-bottom-right-radius: 0;
	border-bottom-left-radius: 0;
}

.form-signin input[type="password"] {
	margin-bottom: 10px;
	border-top-left-radius: 0;
	border-top-right-radius: 0;
} */
@import url('https://fonts.googleapis.com/css?family=Open+Sans');

* {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
}

.logoutBtn {

  align-items: center;
  background-clip: padding-box;
  background-color: #fa6400;
  border: 1px solid transparent;
  border-radius: .25rem;
  box-shadow: rgba(0, 0, 0, 0.02) 0 1px 3px 0;
  box-sizing: border-box;
  color: #fff;
  cursor: pointer;
  display: inline-flex;
  font-family: system-ui,-apple-system,system-ui,"Helvetica Neue",Helvetica,Arial,sans-serif;
  font-size: 16px;
  font-weight: 600;
  justify-content: center;
  line-height: 1.25;
  margin: 0;
  min-height: 3rem;
  padding: calc(.875rem - 1px) calc(1.5rem - 1px);
  position: relative;
  text-decoration: none;
  transition: all 250ms;
  user-select: none;
  -webkit-user-select: none;
  touch-action: manipulation;
  vertical-align: baseline;
  width: auto;
}

.logoutBtn:focus {
  background-color: #fb8332;
  box-shadow: rgba(0, 0, 0, 0.1) 0 4px 12px;
}

.logoutBtn:hover {
  transform: translateY(-1px);
}

.logoutBtn:active {
  background-color: #c85000;
  box-shadow: rgba(0, 0, 0, .06) 0 2px 4px;
  transform: translateY(0);
}


body {
  font-family: 'Open Sans', sans-serif;
  color: #222;
  padding-bottom: 50px;
}

.container {
  max-width: 1200px;
  margin: 0 auto;
  width: fixed;

}

.contaiinerBtn{

  align-self: center;
  margin: auto;
  position: relative;
  padding: 0%;
  
}

.nav {
  position: fixed;
  background-color: #222;
  top: 0;
  left: 0;
  right: 0;
  transition: all 0.3s ease-in-out;
}

.nav .container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 0;
  transition: all 0.3s ease-in-out;
}

.nav ul {
  display: flex;
  list-style-type: none;
  align-items: center;
  justify-content: center;
}

.nav a {
  color: #fff;
  text-decoration: none;
  padding: 7px 15px;
  transition: all 0.3s ease-in-out;
}

.nav.active {
  background-color: #fff;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.3);
}

.nav.active a {
  color: #000;
}

.nav.active .container {
  padding: 10px 0;
}

.nav a.current,
.nav a:hover {
  color: #c0392b;
  font-weight: bold;
}
.ma {
  display: contents;

}
.hero {
  background-image: url('https://images.pexels.com/photos/450035/pexels-photo-450035.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=750&w=1260');
  background-repeat: no-repeat;
  background-size: cover;
  background-position: bottom center;
  height: 100vh;
  color: #fff;
  display: flex;
  justify-content: center;
  align-items: center;
  text-align: center;
  position: relative;
  margin-bottom: 20px;
  z-index: -2;
  /* background-size:100% 100%;
background-attachment:fixed; */
}

.hero::before {
  content: '';
  position: absolute;
  /* background-size:100% 100%;
background-attachment:fixed; */
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  z-index: -1;
}

.hero h1 {
  font-size: 46px;
  margin: -20px 0 20px;
}

.hero p {
  font-size: 20px;
  letter-spacing: 1px;
}

.content h2,
.content h3 {
  font-size: 150%;
  margin: 20px 0;
}

.content p {
  color: #555;
  line-height: 30px;
  letter-spacing: 1.2px;
}

  </style> 
